package com.bobo.medicinechest;

import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bobo.base.BaseActivity;
import com.bobo.base.utils.XToastUtils;
import com.bobo.medicinechest.databinding.ActivityMainBinding;
import com.hnj.dp_nserialportlist.Serialport_Factory;
import com.xpm.serialport.YxSerialHelper;
import com.xpm.serialport.callback.DrugSellSerialCallback;
import com.xpm.serialport.callback.LightBoxControlCallback;
import com.xpm.serialport.callback.LightControlCallback;
import com.xpm.serialport.callback.MachineLightCallback;
import com.xpm.serialport.callback.OpenDoorCallback;
import com.xpm.serialport.callback.RefrigerationControlCallback;
import com.xpm.serialport.callback.SerialInitCallback;
import com.xpm.serialport.callback.TempControlCallBack;
import com.xpm.serialport.callback.TempGetCallBack;
import com.xpm.serialport.data.CheckStatusInfo;
import com.xpm.serialport.data.MotorRequestInfo;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private YxSerialHelper yxSerialHelper;
    private String mDeviceId;
    private CheckStatusInfo mCheckStatusInfo;
    private final int  BORAD = 2;
    private Serialport_Factory serialportFactory;
    private boolean isOpen;

    @Override
    protected ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initListeners() {

    }

    @Override
    protected void initData() {
        yxSerialHelper = YxSerialHelper.getInstance();
        //port默认串口为/dev/ttyS1 daud波特率默认9600
//        yxSerialHelper.setDevice(new Device("1", "9600"));

        //连接设备
        connectSerialPortAndGetId("1");

        findViewById(R.id.tv).setOnClickListener(v -> {
            //连接设备
            connectSerialPortAndGetId("1");
        });

        findViewById(R.id.tv0).setOnClickListener(v -> {
            //商品
            Intent intent = new Intent(this, GoodsListActivity.class);
            startActivity(intent);
        });


        findViewById(R.id.tv1).setOnClickListener(v -> {
            //打开补货灯  id:补货灯电机号
            openLight(3);
        });

        findViewById(R.id.tv2).setOnClickListener(v -> {
            //关闭补货灯
            closeLight();
        });


        findViewById(R.id.tv3).setOnClickListener(v -> {
            //温度湿度控制
            tempControl(BORAD, 15, 50);
        });

        findViewById(R.id.tv4).setOnClickListener(v -> {
            //温度湿度控制
            tempControl(BORAD, 20, 60);
        });


        findViewById(R.id.tv5).setOnClickListener(v -> {
            //定时获取温度湿度
            timingGetTemp(1*60*1000);
        });


        findViewById(R.id.tv6).setOnClickListener(v -> {
            //制冷控制开
            refrigerationControl(BORAD, 1);
        });

        findViewById(R.id.tv66).setOnClickListener(v -> {
            //制冷控制关
            refrigerationControl(BORAD, 0);
        });


        findViewById(R.id.tv7).setOnClickListener(v -> {
            //药柜内照明灯控制 type 1:开启 0:关闭
            machineLightControl(BORAD, 1);
        });

        findViewById(R.id.tv8).setOnClickListener(v -> {
            //药柜内照明灯控制 type 1:开启 0:关闭
            machineLightControl(BORAD, 0);
        });


        findViewById(R.id.tv9).setOnClickListener(v -> {
            //灯箱控制  1开 0关
            lightBoxControl(BORAD, 1);
        });

        findViewById(R.id.tv10).setOnClickListener(v -> {
            //灯箱控制  1开 0关
            lightBoxControl(BORAD, 0);
        });


        findViewById(R.id.tv11).setOnClickListener(v -> {
            //开电动门
            OpenDoorControl(1);
        });
        findViewById(R.id.tv12).setOnClickListener(v -> {
            //关电动门
            OpenDoorControl(0);
        });


        List<MotorRequestInfo> list = new ArrayList<>();

        findViewById(R.id.tv13).setOnClickListener(v -> {
            list.clear();
            //Type  出货类型 0单路电机出货 1多路电机出货
            //Id    电机id
            //Count 多路电机数   仅多路电机出货有效，  比如 id=1，count=2 表示合并 1、2、3号电机。
            //CargoBoard  拓展板地址 1主柜  2副柜
            MotorRequestInfo motorRequestInfo = new MotorRequestInfo();
            motorRequestInfo.setType(1);
            motorRequestInfo.setId(3);
            motorRequestInfo.setCount(0);
            motorRequestInfo.setCargoBoard(1);
            list.add(motorRequestInfo);
            //出货
            startMotor(list,1, 1, 0);
        });

        findViewById(R.id.tv14).setOnClickListener(v -> {
            //连接打印机
            connectSerialPort();
        });

        findViewById(R.id.tv15).setOnClickListener(v -> {
            //检查是否缺纸
            CheckPaper();
        });

        findViewById(R.id.tv16).setOnClickListener(v -> {
            //1标签模式， 2小票打印模式
            setPrintMode(2);
        });

        findViewById(R.id.tv17).setOnClickListener(v -> {
            //打印文本内容
            printText("默认文字居左", 1,1,20);
        });

    }

    /**
     * 连接设备,并获取设备信息
     * @param port 串口号
     */
    private void connectSerialPortAndGetId(String port) {
        yxSerialHelper.connectSerialPortAndGetId(port, new SerialInitCallback() {
            @Override
            public void onConnectSuccess(String s) {
                mDeviceId = s;
                Log.e("=====", "连接成功 设备id=" + s);
                XToastUtils.toast("连接成功 设备id=" + s);
                //定时获取温度湿度
                timingGetTemp(10*60*1000);
            }

            @Override
            public void onConnectError(int i, String s) {
                Log.e("=====", "连接失败 错误码=" + i +" 错误信息=" + s);
                XToastUtils.toast("连接失败 错误码=" + i +" 错误信息=" + s);
            }

            @Override
            public void onPollCommandResponse(CheckStatusInfo checkStatusInfo) {
                //连接成功返回设备信息
                mCheckStatusInfo = checkStatusInfo;
                String str = "state 控制板状态=" + checkStatusInfo.getState()
                        + ",\nmotorIndex 电机索引=" + checkStatusInfo.getMotorIndex()
                        + ",\ncurrentTemp 实时温度=" + checkStatusInfo.getCurrentTemp()
                        + ",\ncurrentHumidity 实时湿度=" + checkStatusInfo.getCurrentHumidity()
                        + ",\ndropLightEyeState  掉货光眼状态=" + checkStatusInfo.getDropLightEyeState()
                        + ",\notherState 其他状态=" + checkStatusInfo.getOtherState()
                        + ",\nconveyorState 传送带状态=" + checkStatusInfo.getConveyorState()
                        + ",\ndoorState 门状态=" + checkStatusInfo.getDoorState()
                        + ",\nisCompressorOpen 压缩机是否已打开=" + checkStatusInfo.isCompressorOpen()
                        + ",\nisLightBoxControllOpen =" + checkStatusInfo.isLightBoxControllOpen()
                        + ",\nisFloodLightOpen 药柜内照明灯是否已打开=" + checkStatusInfo.isFloodLightOpen();
                Log.e("=====", "设备信息 :" + str);
                Toast.makeText(MainActivity.this, "设备信息=" + str, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 打开补货灯
     * @param id
     */
    private void openLight(int id) {
        yxSerialHelper.openLight(id, new LightControlCallback() {
            @Override
            public void onsuccess() {
                Log.e("=====", "打开补货灯成功 ");
                Toast.makeText(MainActivity.this, "打开补货灯成功", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("=====", "打开补货灯失败 i=" + i +" s=" + s);
                Toast.makeText(MainActivity.this, "打开补货灯失败 i=" + i +" s=" + s, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 关闭补货灯
     */
    private void closeLight() {
        yxSerialHelper.closeAllLight(new LightControlCallback() {
            @Override
            public void onsuccess() {
                Log.e("=====", "关闭补货灯成功");
                Toast.makeText(MainActivity.this, "关闭补货灯成功", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("=====", "关闭补货灯失败  i=" + i +" s=" + s);
                Toast.makeText(MainActivity.this, "关闭补货灯失败 i=" + i +" s=" + s, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 温度湿度控制
     * @param board
     * @param tempreture    温度
     * @param humidity      湿度
     */
    private void tempControl(int board, int tempreture, int humidity) {
        yxSerialHelper.tempControl(board, tempreture,humidity, new TempControlCallBack(){

            @Override
            public void onSuccess() {
                Log.e("=====", "温湿度设置成功 温度=" + tempreture + " 湿度=" + humidity);
                Toast.makeText(MainActivity.this, "温湿度设置成功  温度=" + tempreture + " 湿度=" + humidity, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("=====", "温湿度设置失败 i=" + i +" s=" + s);
                Toast.makeText(MainActivity.this, "温湿度设置失败 i=" + i +" s=" + s, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 定时获取温度湿度
     * @param times  10 * 60 * 1000
     */
    private void timingGetTemp(int times) {
        yxSerialHelper.timingGetTemp(times, new TempGetCallBack(){

            @Override
            public void onSuccess(int temp, int humidity) {
                Log.e("=====", "定时获取温度湿度成功 temp=" + temp + " humidity=" + humidity);
                Toast.makeText(MainActivity.this, "定时获取温度湿度成功 temp=" + temp + " humidity=" + humidity, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("=====", "定时获取温度湿度失败 i=" + i +" s=" + s);
                Toast.makeText(MainActivity.this, "定时获取温度湿度失败 i=" + i +" s=" + s, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 制冷控制
     * @param board
     * @param type      类型 1制冷开 0制冷关
     */
    private void refrigerationControl(int board, int type) {
        yxSerialHelper.refrigerationControl(board, type, new RefrigerationControlCallback() {
            @Override
            public void onConnectError() {
                Log.e("=====", "制冷控制失败");
                Toast.makeText(MainActivity.this, "制冷控制失败", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onOtherError(int i, String s) {
                Log.e("=====", "制冷控制其他失败 i=" + i +" s=" + s);
                Toast.makeText(MainActivity.this, "制冷控制 i=" + i +" s=" + s, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onRefrigerationControlSuccess() {
                Log.e("=====", "制冷控制成功");
                Toast.makeText(MainActivity.this, "制冷控制" + (type == 0 ? "关闭成功" : "打开成功"), Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 药柜内照明灯控制
     * @param board
     * @param type 1开启  0关闭
     */
    private void machineLightControl(int board, int type) {
        yxSerialHelper.machineLightControl(board, type, new MachineLightCallback(){

            @Override
            public void onsuccess() {
                Log.e("=====",  "药柜内照明灯" + (type == 0 ? "关闭成功" : "打开成功"));
                Toast.makeText(MainActivity.this, "药柜内照明灯" + (type == 0 ? "关闭成功" : "打开成功"), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("=====", "药柜内照明灯控制失败 i=" + i +" s=" + s);
                Toast.makeText(MainActivity.this, "药柜内照明灯控制失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 灯箱控制
     * @param board
     * @param type    1开 0关
     */
    private void lightBoxControl(int board, int type) {
        yxSerialHelper.lightBoxControl(board, type, new LightBoxControlCallback() {
            @Override
            public void onsuccess() {
                Log.e("=====", "灯箱控制" + (type == 0 ? "关闭成功" : "打开成功"));
                Toast.makeText(MainActivity.this, "灯箱控制" + (type == 0 ? "关闭成功" : "打开成功"), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("=====", "灯箱控制失败  i=" + i +" s=" + s);
                Toast.makeText(MainActivity.this, "灯箱控制失败 i=" + i +" s=" + s, Toast.LENGTH_LONG).show();
            }
        });
    }


    /**
     * 电动门  TODO 非电动门药柜
     * @param type 1开  0关
     */
    private void OpenDoorControl(int type) {
        yxSerialHelper.OpenDoorControl(type, new OpenDoorCallback() {
            @Override
            public void onsuccess() {
                Log.e("=====", "电动门 " + (type == 0 ? "关闭成功" : "打开成功"));
                Toast.makeText(MainActivity.this, "开门成功", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(String s) {
                Log.e("=====", "电动门失败 "+" s=" + s);
                Toast.makeText(MainActivity.this, "开门失败"+" s=" + s, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 出货
     * MotorRequestInfo:要出的货品信息
     * Type:        0 无电动门无传送带 1 无传送带有电动门 2 有传送带有电动门 3 有传送带没电动门
     * sendType:    0 不带升降装置  1 带升降装置
     * Out:         0不重复出药  1重复出药  2重复  10 次出药
     */
    private void startMotor(List<MotorRequestInfo> list, int type, int sendType, int out ) {
        yxSerialHelper.startMotor(list, type, sendType, out,  new DrugSellSerialCallback() {

            @Override
            public void onGoodDropSuccess(MotorRequestInfo motorRequestInfo, int index) {
                //出货是否完成,需要自行根据 index 判断,如: list.size() - 1 == index 表示所有货出货结束
                Log.e("=====", "商品出货成功 motorRequestInfo=" + motorRequestInfo + " index=" + index);
                XToastUtils.toast("商品出货成功 motorRequestInfo=" + motorRequestInfo + " index=" + index);

                //出货是否完成,需要自行根据 index 判断,如: list.size() - 1 == index 表示所有货出货结束。
                if (list.size() -1 == index) {
                    Log.e("=====", "所有货出货结束");
                }
            }

            @Override
            public void onGoodDropError(MotorRequestInfo motorRequestInfo, int index, String s) {
                Log.e("=====", "商品出货失败 motorRequestInfo=" + motorRequestInfo + " index=" + index);
                XToastUtils.toast("商品出货失败 motorRequestInfo=" + motorRequestInfo + " index=" + index);
            }

            @Override
            public void onPollErr(int type, int currentPosition) {
                //出货前轮训指令失败,本次出货所有订单视为异常,  type 0出货前 1出货中
                Log.e("=====", "传送带停止 type=" + type + " currentPosition=" + currentPosition);
            }

            @Override
            public void onConveyorStop() {
                Log.e("=====", "传送带停止");
            }

            @Override
            public void onDoorOpen() {
                Log.e("=====", "电动门开启");
            }

            @Override
            public void onDoorError() {
                Log.e("=====", "电动门开启失败");
            }

            @Override
            public void onDoorClose() {
                Log.e("=====", "电动门关闭");
            }

            @Override
            public void onGoodTakeOver() {
                Log.e("=====", "传送装置启动成功");

            }

            @Override
            public void onSendSucc() {
                Log.e("=====", "传送装置启动成功");
            }

            @Override
            public void onSendError() {
                Log.e("=====", "传送装置启动成功");
            }

            @Override
            public void onOtherError(int i, String s) {
                Log.e("=====", "其他错误回调 i=" + i + " s=" + s);
            }

            @Override
            public void onConnectError() {
                Log.e("=====", "串口连接失败回调");
            }
        });
    }


    private void getPermissions() {
//        XXPermissions.with(this)
//                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
//                .request(new OnPermissionCallback() {
//                    @Override
//                    public void onGranted(List<String> permissions, boolean all) {
                        // 授权成功
                        yxSerialHelper.connectSerialPortAndGetId("1", new SerialInitCallback() {
                            @Override
                            public void onConnectSuccess(String s) {
                                mDeviceId = s;
                                Log.e("=====", "onConnectSuccess 设备id=" + s);
                                XToastUtils.toast("onConnectSuccess 设备info=" + s);
                            }

                            @Override
                            public void onConnectError(int i, String s) {
                                Log.e("=====", "onConnectError i=" + i +" s=" + s);
                                XToastUtils.toast("onConnectSuccess i=" + i +" s=" + s);
                            }

                            @Override
                            public void onPollCommandResponse(CheckStatusInfo checkStatusInfo) {
                                Log.e("=====", "onPollCommandResponse " + checkStatusInfo);
                            }
                        });
//                    }
//
//                    @Override
//                    public void onDenied(List<String> permissions, boolean never) {
//                            XToastUtils.toast("获取权限失败");
//                    }
//                });
    }


    private static final String SEARCH_INFO_PORD = "ttyS3";
    private static final String BAUD_RATE = "115200";

    private void connectSerialPort() {
        serialportFactory = Serialport_Factory.getSerialport_Factory(MainActivity.this);
        //串口名称 ttyS0或ttySAC0   baudrate波特率
        isOpen = serialportFactory.OpenPort(SEARCH_INFO_PORD, BAUD_RATE);
        LogUtils.e("====isOpen:" + isOpen);
        if (isOpen) {
            LogUtils.e("====打印机已连接======");
            ToastUtils.showShort("打印机已连接");
        } else {
            LogUtils.e("打印机连接失败，串口号:" + SEARCH_INFO_PORD + " 波特率:" + BAUD_RATE);
        }

        //获取所有串口设备名称。
//        String[] allDevices = serialportFactory.getAllDevices();
//        for (int i = 0; i < allDevices.length; i++) {
//            LogUtils.e(allDevices[i]);
//        }
    }

    /**
     * 检查是否缺纸
     */
    private void CheckPaper() {
        serialportFactory.Check_Paper();

    }

    /**
     *  设置打印模式
     *  1标签模式， 2小票打印模式
     */
    private void setPrintMode(int type) {
        serialportFactory.setprintmode(type);
    }

    /**
     *  打印文本内容
     *  第一个参数 text  打印文本内容字符串
     * 第二个参数Align_Type对齐方式传送的值 1(左对齐)，2(居中)，3(右对齐)
     * 第三个参数Char_Zoom_Num 字符缩放大小1（默认正常字体）   2（字体放大一倍）    3（字体倍宽）  4 （字体倍高）
     * 第四个参数Line_spac  行距 有效值未 10 20 30 40 50 60
     */
    private void printText(String content, int alignType, int charZoomNum, int lineSpac) {
        serialportFactory.PrintText(content,alignType,charZoomNum,lineSpac);
    }
}